package com.distribute.application.api.rest.member;

import java.security.spec.AlgorithmParameterSpec;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.IpUtil;
import com.distribute.application.api.utils.PayUtil;
import com.distribute.framework.model.Agent;
import com.distribute.framework.model.BalanceDetails;
import com.distribute.framework.model.Commodity;
import com.distribute.framework.model.Configur;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.Distributor;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.Merchant;
import com.distribute.framework.model.OrderDetails;
import com.distribute.framework.model.PackRecord;
import com.distribute.framework.model.Parameter;
import com.distribute.framework.model.Product;
import com.distribute.framework.model.ProductDetails;
import com.distribute.framework.model.ProductOrder;
import com.distribute.framework.model.RedPacket;
import com.distribute.framework.model.ShoppingCart;
import com.distribute.framework.model.SrvOauth;
import com.distribute.framework.model.UserAddress;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;
@RestController(value="api.MemberBalanceController")
public class MemberBalanceController  extends BaseApiController{
	/**
	 * 会员余额充值订单提交
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/balance/yuEOrderT.do")
	public @title("会员余额充值订单提交")  Protocol yuEOrderT(
//			@title("商品编号") String idsw,
//			@title("充值数") String chongw,
			@title("品牌") Long merchant,
			@title("数据") String jsons,
			@title("总金额") Double sums
			) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		JSONArray jsonArray= JSON.parseArray(jsons);
		Double double1=0.0;
		if(jsonArray.size()>0){
			for(int i=0;i<jsonArray.size();i++) {
				JSONObject jObject=jsonArray.getJSONObject(i);
				Integer chong=jObject.getInteger("chong");
				Integer zeng=jObject.getInteger("zeng");
				Double price=jObject.getDouble("price");
				if (chong!=null) {
					double1=double1+chong*price;
				}
				if (zeng!=null) {
					double1=double1+zeng*price;
				}
			}
		}
		String orderNo=new Date().getTime()*3+"-"+member.getId()+"-"+merchant;
		ProductOrder productOrder=new ProductOrder(
				orderNo
			 	,merchant//所属品牌 [非空]
			 	,member.getUid$()
			 	,member.getId()//会员信息 [非空]
			 	,jsons//购买时价格
			 	,Arith.round(double1, 2)//价值金额
			 	,(short)0
			 	,sums//支付金额
			 	,null//支付时间
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
				);
		productOrder.save();
		ProductOrder productOrde=ProductOrder.where.orderNumber(orderNo).get();
		String pay_url=Utils.config("conf.wxpayurl");
		String notify_url=Utils.config("conf.host")+"/api/orders/chongGouModify.wx";//回调接口地址
		
        //生成的随机字符串  
    	 String nonce_str = IpUtil.getRandomStringByLength(32); 
        //商品名称  
        String body = "产品余额充值";  
        //获取客户端的ip地址  
        String spbill_create_ip = IpUtil.getIpAddr(Utils.getServletRequest());
        System.out.println("真实IP地址"+spbill_create_ip);
        DecimalFormat decimalFormat = new DecimalFormat("###################.###########");
        String money=decimalFormat.format(productOrde.getPayment()*100);
      //String spbill_create_ip = "127.0.0.1";
        //组装参数，用户生成统一下单接口的签名  
        Map<String, String> packageParams = new HashMap<String, String>();  
        packageParams.put("appid", Utils.config("wx.mp1.appid"));  
        packageParams.put("mch_id", Utils.config("wx.mch1.id"));  
        packageParams.put("nonce_str", nonce_str);  
        packageParams.put("body", body);  
        packageParams.put("out_trade_no", productOrde.getOrderNumber());//商户订单号  
        packageParams.put("total_fee", money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
        packageParams.put("spbill_create_ip", spbill_create_ip);  
        packageParams.put("notify_url", notify_url);//支付成功后的回调地址  
        packageParams.put("trade_type", "JSAPI");//支付方式  
        packageParams.put("openid", member.getOpenid());  
        System.out.println("appid"+ Utils.config("wx.mp1.appid"));
        System.out.println("mch_id"+ Utils.config("wx.mch1.id"));  
        System.out.println("nonce_str"+nonce_str);  
        System.out.println("body"+ body);  
        System.out.println("out_trade_no"+productOrde.getOrderNumber());//商户订单号  
        System.out.println("total_fee"+money);//支付金额，这边需要转成字符串类型，否则后面的签名会失败  
        System.out.println("spbill_create_ip"+spbill_create_ip);  
        System.out.println("notify_url"+notify_url);//支付成功后的回调地址  
        System.out.println("trade_type"+"JSAPI");//支付方式  
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串   
          
            //MD5运算生成签名，这里是第一次签名，用于调用统一下单接口  
            String mysign = PayUtil.sign(prestr, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
          
        //拼接统一下单接口使用的xml数据，要将上一步生成的签名一起拼接进去  
        String xml = "<xml>" + "<appid>" +Utils.config("wx.mp1.appid") + "</appid>"   
                + "<body><![CDATA[" + body + "]]></body>"   
                + "<mch_id>" +  Utils.config("wx.mch1.id") + "</mch_id>"   
                + "<nonce_str>" + nonce_str + "</nonce_str>"   
                + "<notify_url>" + notify_url + "</notify_url>"   
                + "<openid>" + member.getOpenid() + "</openid>"   
                + "<out_trade_no>" + productOrde.getOrderNumber() + "</out_trade_no>"   
                + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"   
                + "<total_fee>" + money + "</total_fee>"  
                + "<trade_type>" + "JSAPI" + "</trade_type>"   
                + "<sign>" + mysign + "</sign>"  
                + "</xml>";  
          
        System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);  
        //调用统一下单接口，并接受返回的结果  
        String result = PayUtil.httpRequest(pay_url, "POST", xml);  
        System.out.println("调试模式_统一下单接口 返回XML数据：" + result);  
        // 将解析结果存储在HashMap中     
        Map map = PayUtil.doXMLParse(result);  
        String return_code = (String) map.get("return_code");//返回状态码  
          
        System.out.println("调试模式_统一下F返回状态" + return_code);  
        if(return_code.equals("SUCCESS")){     
            String prepay_id = (String) map.get("prepay_id");//返回的预付单信息     
            protocol.set("nonceStr", nonce_str);  
            protocol.set("package", "prepay_id=" + prepay_id);  
            Long timeStamp = System.currentTimeMillis() / 1000;     
            protocol.set("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串，不然小程序端调用wx.requestPayment方法会报签名错误  
            //拼接签名需要的参数  
            String stringSignTemp = "appId=" + Utils.config("wx.mp1.appid") + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;     
            //再次签名，这个签名用于小程序端调用wx.requesetPayment方法  
            String paySign = PayUtil.sign(stringSignTemp, Utils.config("wx.mch1.key"), "utf-8").toUpperCase();  
            protocol.set("type", 1); 
            protocol.set("paySign", paySign);  
            protocol.set("appid", Utils.config("wx.mp1.appid")); 
            protocol.setSuccess(true);
        }else {
        	protocol.setSuccess(false);
        	protocol.setMessage("支付失败");
		}  
          
		
		return protocol;
	}
	/**
	 * 会员余额充值获取商品详情
	 * @return
	 */
	@RequestMapping("/api/balance/blanceDetail.do")
	public @title("会员余额充值获取商品详情")  Protocol blanceDetail(
			@title("商品编号") Long goodsId
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Commodity commodity = Commodity.where.id(goodsId).get();
		protocol.set("goods", commodity.toJSON());
		Agent agent=Agent.where.member(member.getId()).merchant(commodity.getMerchant()).status((short)1).get();			
		if (agent==null) {
			protocol.set("agentType", 1);//普通分销员
		}else {
			protocol.set("agentType", 2);//品牌代理商
		}
		return protocol;
	}
	
	@RequestMapping("/api/balance/productDetailsList.do")
	public @title("根据获取产品余额列表接口2")  Protocol productDetailsList(
		@title("页码") Integer pageNo
		,@title("个数") Integer pageSize
		,@title("banrdId") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		
		protocol.setPage(ProductDetails.where.member(member.getId()).brand(banrdId).page(Utils.or(pageNo,0), Utils.or(pageSize,20)), new Protocol.BeanFormat<ProductDetails>(){
			@Override
			public Map format(ProductDetails t) {
				Map json = t.toJSON();
				Commodity commodity=Commodity.where.id(t.getCommodity()).get();
				json.put("goods", commodity.toJSON());
				return json;
			}
		});
		return protocol;
	}
	@RequestMapping("/api/balance/productlist.do")
	public @title("根据品牌信息获取产品余额列表*")  Protocol productlist(
		@title("页码") Integer pageNo
		,@title("个数") Integer pageSize
		,@title("banrdId") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		
		protocol.setPage(Product.where.member(member.getId()).definex("number>0").merchant(banrdId).page(Utils.or(pageNo,0), Utils.or(pageSize,10000)), new Protocol.BeanFormat<Product>(){
			@Override
			public Map format(Product t) {
				Map json = t.toJSON();
				Commodity commodity=Commodity.where.id(t.getCommodity()).get();
				if (commodity.getOptions()!=null&&!commodity.getOptions().equals("")) {
					List<Map<String, Object>> arrList=(List<Map<String, Object>>) Utils.eval(commodity.getOptions());
					if (arrList.size()>0) {
						   List<Map<String, Object>> parent=new ArrayList<Map<String,Object>>();
						for (Map<String, Object> map : arrList) {
							if (map.get("puid")==null) {
								parent.add(map);
							}
						}
						  for (Map<String, Object> map2 : parent) {
							  List<Map<String, Object>> child=new ArrayList<Map<String,Object>>();
							  for (Map<String, Object> map : arrList) {
									if (map.get("puid")!=null&&map2.get("uuid").toString().equals(map.get("puid").toString())) {
										child.add(map);
									}
								}
							  map2.put("child", child);
						}
						  json.put("optioss", parent);
					}else {
						json.put("optioss", "");
					}
				}else {
					json.put("optioss", "");
				}
				return json;
			}
		});
		return protocol;
	}
	
	/**
	 * 购物车提交订单
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 */
	@RequestMapping("/api/balance/carConfirmOrder.do")
	public @title("购物车提交订单")  Protocol carConfirmOrder(
			@title("品牌Id") Long banrdId,
			@title("参数集") String jsons
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		Merchant merchant=Merchant.where.id(banrdId).get();
		String orderNo=new Date().getTime()*3+"-"+member.getId()+"-"+merchant.getId();
		DirectOrder directOrder=new DirectOrder(
				orderNo//订单号 [非空]
			 	,merchant.getId()//所属品牌 [非空]
			 	,""
			 	,(short)1//订单类型       
				,member.getNickName()
			 	,member.getId()//会员信息 [非空]
			 	,""//备注信息
			 	,null//物流方式 [非空]
			 	,""//送货地址 [非空]
			 	,null
			 	,""//经度
			 	,""//纬度
			 	,null//所属地区
			 	,""//收货人姓名
			 	,""//收货人电话
			 	,null//性别
			 	,""//快递单号
			 	,(short)2//
			 	,""
			 	,null//配送商
			 	,0.0
			 	,(short)3//接单类型
			 	,""//自提地址
			 	,null//配送费 [非空]
			 	,null//使用优惠券
			 	,""//使用产品券
			 	,0.0//优惠卷抵扣
			 	,0.0//产品卷抵扣
			 	,0.0//总金额
			 	,0.0//实际支付
			 	,(short)0//支付情况
			 	,(short)0//支付协议
			 	,null//实际处理方 [非空]
			 	,(short)0//售后类型
			 	,""//投诉意见
			 	,(short)0//投诉是处理 [非空]
			 	,(short)0//退款状态 [非空]
			 	,""
			 	,""
			 	,""
				,null
				,""
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
			 	,null
				);
		directOrder.save();
		DirectOrder directOrde=DirectOrder.where.no(orderNo).get();
		Parameter parameter=Parameter.where.merchant(directOrde.getMerchant()).get();
		double sum=0.0;//总金额
		JSONArray jsonArray= JSON.parseArray(jsons);
		for(int i=0;i<jsonArray.size();i++) {
			JSONObject jObject=jsonArray.getJSONObject(i);
			ShoppingCart shoppingCart=ShoppingCart.where.id(jObject.getLong("id")).get();
			OrderDetails orderDetails=new OrderDetails(
					shoppingCart.getNames()//商品名称 [非空]
				 	,directOrde.getId()//所属订单 [非空]
				 	,shoppingCart.getGoods()//商品编号
				 	,shoppingCart.getImg()//商品图
				 	,shoppingCart.getPrice()//商品价格 [非空]
				 	,jObject.getInteger("count")//数量 [非空]
				 	,shoppingCart.getAttribute()
				 	,Arith.round(Arith.mul(parameter.getpPsYj(), Arith.mul(shoppingCart.getPrice(), jObject.getInteger("count"))), 2)
				 	,new Date()//修改时间 [非空]
				 	,new Date()//添加时间 [非空]
				 	,(short)1//状态 [非空]
					);
			orderDetails.save();
			sum=Arith.round(Arith.add(sum, Arith.mul(shoppingCart.getPrice(), jObject.getDouble("count"))), 2);
			shoppingCart.delete();
		}
		directOrde.setActualPay(sum);
		directOrde.setTotalSum(sum);
		directOrde.update();
		protocol.set("orderId", directOrde.getId());
		return protocol;
	}
	/**
	 * 提货提交订单
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 */
	@RequestMapping("/api/balance/balanceGetGoods.do")
	public @title("提货提交订单")  Protocol balanceGetGoods(
			@title("品牌Id") Long banrdId,
			@title("产品数量集") String counts,
			@title("产品属性集") String pty,
			@title("产品IDS") String ids
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		Merchant merchant=Merchant.where.id(banrdId).get();
		String orderNo=new Date().getTime()*3+"-"+member.getId()+"-"+merchant.getId();
		DirectOrder directOrder=new DirectOrder(
				orderNo//订单号 [非空]
			 	,merchant.getId()//所属品牌 [非空]
			 	,""
			 	,(short)2//订单类型
				,member.getNickName()
			 	,member.getId()//会员信息 [非空]
			 	,""//备注信息
			 	,null//物流方式
			 	,""//送货地址
			 	,null
			 	,""//经度
			 	,""//纬度
			 	,null//所属地区
			 	,""//收货人姓名
			 	,""//收货电话号
			 	,null//性别
			 	,""//快递单号
			 	,(short)2//配送方式
			 	,""
			 	,null//配送商
			 	,0.0
			 	,(short)3//接单类型
			 	,""//自提地址
			 	,null//配送费 [非空]
			 	,null//使用优惠券
			 	,""//使用产品券
			 	,0.0//优惠卷抵扣
			 	,0.0//产品卷抵扣
			 	,0.0//总金额
			 	,0.0//实际支付 [非空]
			 	,(short)0//支付情况
			 	,(short)0//支付协议
			 	,null//实际处理方 [非空]
			 	,(short)0//售后类型
			 	,""//投诉意见
			 	,(short)0//投诉是处理 [非空]
			 	,(short)0//退款状态 [非空]
			 	,""//拒绝退款理由
			 	,""//会员退款理由
			 	,""
			 	,null//接单时间
			 	,""
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
			 	,null
				);
		directOrder.save();
		DirectOrder directOrde=DirectOrder.where.no(orderNo).get();
		String[] idArray=ids.substring(0, ids.length()-1).split(",");
		String[] ptyArray=pty.substring(0, pty.length()-1).split(",");
		String[] countsArray=counts.substring(0, counts.length()-1).split(",");
		double sum=0.0;
		Parameter parameter=Parameter.where.merchant(directOrde.getMerchant()).get();
		List<Map<String, Object>> lists=new ArrayList<Map<String,Object>>();
		double zyj=0.0;
		for (int i = 0; i < idArray.length; i++) {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("id", idArray[i]);
			map.put("count", countsArray[i]);
			lists.add(map);
			Product product=Product.where.id(Long.valueOf(idArray[i])).get();
			Commodity commodity=Commodity.where.id(product.getCommodity()).get();
			System.out.println("getpPsYj"+parameter.getpPsYj());
			System.out.println("getPrice"+commodity.getPrice());
			System.out.println("countsArray"+countsArray[i]);
			System.out.println("配送佣金"+Arith.round(parameter.getpPsYj()*commodity.getPrice()*Integer.valueOf(countsArray[i])*0.7, 2));
			double yjs=Arith.round(parameter.getpPsYj()*commodity.getPrice()*Integer.valueOf(countsArray[i])*0.7, 2);
			zyj=zyj+yjs;
			System.out.println("配送佣金2"+yjs);
			OrderDetails orderDetails=new OrderDetails(
					commodity.getName()//商品名称 [非空]
				 	,directOrde.getId()//所属订单 [非空]
				 	,commodity.getId()//商品编号
				 	,commodity.getImage()//商品图
				 	,commodity.getPrice()//商品价格 [非空]
				 	,Integer.valueOf(countsArray[i])//数量 [非空]
				 	,ptyArray[i]//所选属性
				 	,yjs
				 	,new Date()//修改时间 [非空]
				 	,new Date()//添加时间 [非空]
				 	,(short)1//状态 [非空]
					);
			orderDetails.save();
			BalanceDetails balanceDetails=new BalanceDetails(
					banrdId//品牌 [非空]
				 	,member.getId()// [非空]
				 	,directOrde.getId()//所属订单 [非空]
				 	,Integer.valueOf(countsArray[i])//消费数量 [非空]
				 	,product.getId()//余额产品 [非空]
					);
			balanceDetails.save();
			sum=sum+commodity.getPrice()*Integer.valueOf(countsArray[i]);
		}
		directOrde.setDistributorIncome(zyj);
		directOrde.update();
		directOrde.setProductFree(sum);
		directOrde.setUseProductVouchers(JSON.toJSONString(lists));
		directOrde.setTotalSum(sum);
		directOrde.update();
		protocol.set("orderId", directOrde.getId());
		return protocol;
	}
	
	/**
	 * 获取提交订单详情
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 */
	@RequestMapping("/api/balance/getOrderInfos.do")
	public @title("获取提交订单详情")  Protocol getOrderInfos(
			@title("订单Id") Long orderId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		List<OrderDetails> orderDetails=OrderDetails.where.orders(directOrder.getId()).list(100);
		 long coupons=0;
		 Integer products=0;
		 Double sumDouble=0.0;
		 for (OrderDetails orderDetails2 : orderDetails) {
			 sumDouble=Arith.round(Arith.add(sumDouble, Arith.mul(orderDetails2.getPrice(), orderDetails2.getNumber())), 2);
			 Product product=Product.where.member(member.getId()).merchant(directOrder.getMerchant()).commodity(orderDetails2.getGoodsNumber()).get();
				if (product!=null) {
					products+=product.getNumber();
				}
				coupons+=Coupon.where.member(member.getId()).merchant(directOrder.getMerchant()).isOk((short)0).useStatus((short)1).commodity(orderDetails2.getGoodsNumber()).count();
		}
		protocol.setList(orderDetails, new Protocol.BeanFormat<OrderDetails>(){
			@Override
			public Map format(OrderDetails t) {
				Map json = t.toJSON();
				return json;
			}
		});
		Parameter parameter=Parameter.where.merchant(directOrder.getMerchant()).get();
		double diriFree=0.0;
		for (OrderDetails orderDetails2 : orderDetails) {
			Commodity commodity=Commodity.where.id(orderDetails2.getGoodsNumber()).get();
			diriFree=commodity.getDistriFee();
		   Integer countss=orderDetails2.getNumber()-1;
		   if (countss>0) {
			   diriFree=Arith.round(Arith.add(diriFree, Arith.mul(countss, commodity.getOverFee())), 2);;
		   }
		}
		if (directOrder.getTotalSum()>=parameter.getFullFee()) {
			protocol.set("peisong", 0);
		}else {
			protocol.set("peisong", diriFree);
		}
		Merchant merchant=Merchant.where.id(directOrder.getMerchant()).get();
		UserAddress userAddress=UserAddress.where.member(member.getId()).isDefault((short)1).get();
		if (userAddress!=null) {
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("address", userAddress.getAddress());
			map.put("coordinate","");
			map.put("member$", userAddress.getMember$());
			map.put("latitude",userAddress.getLatitude());
			map.put("mobile", userAddress.getMobile());
			map.put("cityOrigin", userAddress.getCityOrigin());
			map.put("realName$", userAddress.getRealName());
			map.put("address$", userAddress.getAddress$());
			map.put("realName", userAddress.getRealName());
			map.put("isDefault", userAddress.getIsDefault());
			map.put("member", userAddress.getMember());
			map.put("fullAddress", userAddress.getFullAddress());
			map.put("detailAddress", userAddress.getDetailAddress());
			map.put("id", userAddress.getId());
			map.put("cityOrigin$", userAddress.getCityOrigin$());	
			map.put("longitude", userAddress.getLongitude());
			protocol.set("address", map);
		}else {
			protocol.set("address", null);
		}
		protocol.set("banrd", merchant.toJSON(true));
		Map oMap=directOrder.toMap();
		oMap.put("bname", directOrder.getMerchant$());
		protocol.set("order", directOrder.toMap());
		protocol.set("coupons", coupons);
		protocol.set("products", products);
		protocol.set("sumDouble", sumDouble);
		return protocol;
	}
	/**
	 * 会员查看订单的详情
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 */
	@RequestMapping("/api/balance/getOrderDetailInfos.do")
	public @title("会员查看订单的详情")  Protocol getOrderDetailInfos(
			@title("订单Id") Long orderId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		List<OrderDetails> orderDetails=OrderDetails.where.orders(directOrder.getId()).list(100);
		protocol.setList(orderDetails, new Protocol.BeanFormat<OrderDetails>(){
			@Override
			public Map format(OrderDetails t) {
				Map json = t.toJSON();
				return json;
			}
		});
		if (directOrder.getDistributor()!=null) {
			Distributor distributor=Distributor.where.id(directOrder.getDistributor()).get();
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("name", distributor.getName());
			map.put("mobile", distributor.getMobile());
			map.put("address", distributor.getCoordinateAddress());
			map.put("deliveryTime", distributor.getDeliveryTime$());
			map.put("long", distributor.getLongitude());
			map.put("lan", distributor.getLatitude());
			protocol.set("dot", map);
		}else {
			protocol.set("dot", null);
		}
		protocol.set("order", directOrder.toMap());
		return protocol;
	}
	/**
	 * 会员领红包前获取红包信息
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 */
	@RequestMapping("/api/balance/getRedInfo.do")
	public @title("会员领红包前获取红包信息")  Protocol getRedInfo(
			@title("红包Id") Long redId,
			@title("品牌ID")Long banrnId
	){
		Protocol protocol = Protocol.create(true, null);
		RedPacket redPacket=RedPacket.where.id(redId).get();
		if(banrnId!=null){
			Parameter parameter=Parameter.where.merchant(banrnId).get();
			protocol.set("parma", parameter.toJSON());
		}
		protocol.set("validity", redPacket.getStatus()==(short)0||new Date().getTime()>=redPacket.getValidity().getTime()?1:0);
		protocol.set("setting", Configur.where.get().toJSON());
		protocol.set("red", redPacket.toJSON());
		return protocol;
	}
	
	/**
	 * 会员领取红包接口
	 * @param counts
	 * @param pty
	 * @param ids
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/api/balance/getRed.do")
	public @title("会员领取红包接口")  Protocol getRed(
			@title("vi") String vi,
			@title("encData") String encData,
			@title("session_key") String session_key,
			@title("openid") String openid,
			@title("红包Id") Long redId
	) throws Exception{
		Protocol protocol = Protocol.create(true, null);
		RedPacket redPacket=RedPacket.where.id(redId).get();
		Member member=Member.where.openid(openid).get();//根据openId查找用户
		if(redPacket.getRedEnveloper().toString().equals(member.getId().toString())){
			 protocol.set("banrd", redPacket.getMerchant());
			  protocol.set("msg", "不能领取自己的红包");
				 protocol.set("type", 4);
				 return protocol;
		}
		if (member!=null) {//不是新用户就 修改手机号码
			 SrvOauth srvOauth = SrvOauth.where.soTicket(openid).get();
				if(srvOauth==null){
					srvOauth=new SrvOauth();
					srvOauth.setSoToken(Utils.md5(session_key));
					srvOauth.setSoTicket(openid);
					srvOauth.setSoParams(session_key);
					srvOauth.setSoUserId(member.getId());
					srvOauth.setSoApiClient(this.getClient());
					srvOauth.setSoUpdateTime(new Date());
					srvOauth.save();
				}else{
					srvOauth.setSoToken(Utils.md5(session_key));
					srvOauth.setSoTicket(openid);
					srvOauth.setSoParams(session_key);
					srvOauth.setSoUserId(member.getId());
					srvOauth.setSoApiClient(this.getClient());
					srvOauth.setSoUpdateTime(new Date());
					srvOauth.update();
				}
			String jsonObject = decrypt( Base64.decodeBase64(session_key),Base64.decodeBase64(vi),Base64.decodeBase64(encData));
			JSONObject jObject=JSON.parseObject(jsonObject);
			member.setMobile(jObject.getString("phoneNumber"));
			member.update();
			  redPacket.getValidity();
			  if(new Date().getTime()>=redPacket.getValidity().getTime()){
				  protocol.set("banrd", redPacket.getMerchant());
				  protocol.set("msg", "红包已过期");
					 protocol.set("type", 1);
					 return protocol;
			  }
			 if (redPacket.getTypes()==(short)1) {//单人红包     一个人全部领取
				 PackRecord packRed=PackRecord.where.receiver(member.getId()).redEnvelopes(redPacket.getId()).get();
				 if(packRed==null){
				 Integer num=redPacket.getQuantity();
				 if (num>0) {
					 Product product=Product.where.id(redPacket.getProduct()).get();
						 Product product2=Product.where.merchant(product.getMerchant()).member(member.getId()).commodity(product.getCommodity()).get();
						 if (product2==null) {
							 Product products=new Product(
								     product.getName()//名称 [非空]
								 	,product.getMerchant()//品牌信息
								 	,member.getUid$()
								 	,member.getId()//所属会员
								 	,product.getCommodity()//商品信息
								 	,product.getpPrice()
								 	,product.getpUnit()
								 	,product.getImg()
								 	,num//数量
								 	,0
								 	,""//规格属性
								 	,0//预留字段
								 	,"红包领取"//来源描述
								 	,getThreeYear()
								 	,new Date()//修改时间 [非空]
								 	,new Date()//添加时间 [非空]
								 	,(short)1//状态 [非空]
								 );
						     products.save();
						     redPacket.setRecipients(redPacket.getRecipients()+1);
							 redPacket.setQuantity(0);
							 redPacket.update();
							 ProductDetails productDetails=new ProductDetails(
										"红包领取"//获得方式
									 	,product.getMerchant()//品牌信息
									 	,member.getId()//所属会员
									 	,product.getCommodity()//商品信息
									 	,product.getpPrice()
									 	,num//数量
									 	,0
									 	,0
									 	,new Date()//获得时间 [非空]
									 	,(short)1//状态 [非空]
										);
								productDetails.save();
						}else {
							 ProductDetails productDetails=new ProductDetails(
										"红包领取"//获得方式
									 	,product.getMerchant()//品牌信息
									 	,member.getId()//所属会员
									 	,product.getCommodity()//商品信息
									 	,product.getpPrice()
									 	,num//数量
									 	,0
									 	,0
									 	,new Date()//获得时间 [非空]
									 	,(short)1//状态 [非空]
										);
								productDetails.save();
							product2.setNumber(product2.getNumber()+num);
							product2.update();
							  redPacket.setRecipients(redPacket.getRecipients()+1);
								 redPacket.setQuantity(0);
								 redPacket.update();
						}
						 PackRecord packRecord=new PackRecord(
								 member.getId()//领取人
								 	,redPacket.getId()//所属红包
								 	,new Date()
								 );
						 packRecord.save();
						 protocol.set("banrd", redPacket.getMerchant());
						 protocol.set("msg", "领取成功");
						 protocol.set("type", 2);
					 
				 }else {
					 protocol.set("banrd", redPacket.getMerchant());
					 protocol.set("msg", "红包已领完了");
					 protocol.set("type", 3);
					return protocol;
				}
				 }else{
					 protocol.set("banrd", redPacket.getMerchant());
					 protocol.set("msg", "您已领取过该红包了!");
					 protocol.set("type", 3);
					return protocol;
				 }
				}else if(redPacket.getTypes()==(short)2){//多人红包 每人只能领一个
					PackRecord packRecord2=PackRecord.where.receiver(member.getId()).redEnvelopes(redPacket.getId()).get();
					if (packRecord2==null) {
						if (redPacket.getQuantity()>0) {
							 Product product=Product.where.id(redPacket.getProduct()).get();
								 Product product2=Product.where.merchant(product.getMerchant()).member(member.getId()).commodity(product.getCommodity()).get();
								 ProductDetails productDetails=new ProductDetails(
											"红包领取"//获得方式
										 	,product.getMerchant()//品牌信息
										 	,member.getId()//所属会员
										 	,product.getCommodity()//商品信息
										 	,product.getpPrice()
										 	,1//数量
										 	,0
										 	,0
										 	,new Date()//获得时间 [非空]
										 	,(short)1//状态 [非空]
											);
									productDetails.save();
								 if (product2==null) {
								 Product products=new Product(
										     product.getName()//名称 [非空]
										 	,product.getMerchant()//品牌信息
										 	,member.getUid$()
										 	,member.getId()//所属会员
										 	,product.getCommodity()//商品信息
										 	,product.getpPrice()
										 	,product.getpUnit()
										 	,product.getImg()
										 	,1//数量
										 	,0
										 	,""//规格属性
										 	,0//预留字段
										 	,"红包领取"//来源描述
										 	 ,getThreeYear()
										 	,new Date()//修改时间 [非空]
										 	,new Date()//添加时间 [非空]
										 	,(short)1//状态 [非空]
										 );
								 products.save();
								 redPacket.setRecipients(redPacket.getRecipients()+1);
									redPacket.setQuantity(redPacket.getQuantity()-1);
									  redPacket.update();
								 }else {
										product2.setNumber(product2.getNumber()+1);
										product2.update();
										redPacket.setRecipients(redPacket.getRecipients()+1);
										redPacket.setQuantity(redPacket.getQuantity()-1);
										  redPacket.update();
								}
								 PackRecord packRecord=new PackRecord(
										 member.getId()//领取人
										 	,redPacket.getId()//所属红包
										 	,new Date()
										 );
								 packRecord.save();
								 protocol.set("banrd", redPacket.getMerchant());
								 protocol.set("msg", "领取成功");
								 protocol.set("type", 2);
							
						 }else {
							 protocol.set("banrd", redPacket.getMerchant());
							 protocol.set("msg", "红包已领完了");
							 protocol.set("type", 3);
							return protocol;
						}
					}else {
						 protocol.set("banrd", redPacket.getMerchant());
						 protocol.set("msg", "您已领取过该红包");
						 protocol.set("type", 4);
					}
				}
		}
		protocol.set("banrd", redPacket.getMerchant());
		protocol.set("type", 0);
		return protocol;
	}
	private Date getThreeYear() {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
        c.add(Calendar.YEAR, 3);
        Date y = c.getTime();
		return y;
	}
	 public static String decrypt(byte[] key, byte[] iv, byte[] encData) throws Exception {
	        AlgorithmParameterSpec ivSpec = new IvParameterSpec(iv);
	        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	        SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
	        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
	        //解析解密后的字符串
	        return new String(cipher.doFinal(encData),"UTF-8");
	    }
	//@2016-12-13  获取当前时间，指定前面多少小时的时间
	//返回格式YYYYMMDDHHMMSS
	public static Date getArfterHourTime(int ihour){
		String returnstr = "";
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + ihour);
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		return calendar.getTime();
	}
	/**
	 * 发送红包提交订单
	 * @param count
	 * @param type
	 * @param id
	 * @return
	 */
	@RequestMapping("/api/balance/sendRed.do")
	public @title("发送红包提交订单")  Protocol sendRed(
			@title("产品数量") Integer count,
			@title("红包类型1:单人红包,2多人红包") Short type,
			@title("产品ID") Long id
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		Product product=Product.where.id(id).get();
		Parameter parameter=Parameter.where.merchant(product.getMerchant()).get();
		Date timeDate=null;
		if (parameter!=null) {
			Integer timeCount=parameter.getValidity();
			if (timeCount!=null&&timeCount>0) {
				 timeDate=getTimeByHour(timeCount);
			}else {
				timeDate=getTimeByHour(1);
			}
		}else {
			timeDate=getTimeByHour(1);
		}
		
		String unique=member.getId()+new Date().getTime()+"";
		new RedPacket(
			 	product.getMerchant()//品牌信息 [非空]
			 	,member.getId()//发红包人 [非空]
			 	,count//红包数量 [非空]
			 	,product.getId()//余额产品 [非空]
			 	,type//红包类型 [非空]
			 	,timeDate//默认有效期 [非空]
			 	,0//已领取人数 [非空]
			 	,unique
			 	,new Date()//修改时间 [非空]
			 	,new Date()//发放时间 [非空]
			 	,(short)1//状态 [非空]
				).save();
		RedPacket redPacket=RedPacket.where.unique(unique).get();
		product.setNumber(product.getNumber()-count);
		product.update();
		protocol.set("redId", redPacket.getId());
		protocol.set("setting", parameter.toJSON());
		protocol.set("memberId", member.getId());
		return protocol;
	}
	private Date getTimeByHour(int timeCount) {
		  Calendar calendar = Calendar.getInstance();

	        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + timeCount);

	        return calendar.getTime();
	}
}
